import {
  Card,
  Tabs,
  List,
  Tag,
  Button,
  Avatar,
  Space,
  Progress,
  message,
  Badge,
} from "antd"
import { useState, useEffect } from "react"
import {
  ClockCircleOutlined,
  CheckCircleOutlined,
  SyncOutlined,
  UserOutlined,
  CalendarOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons"
import PageHeaderWrapper from "@/components/pageHeaderWrapper"
import "./index.less"

function MyCollaboration() {
  const [activeTab, setActiveTab] = useState("todo")
  const [loading, setLoading] = useState(false)
  const [tasks, setTasks] = useState({
    todo: [],
    inProgress: [],
    completed: [],
  })

  // 获取任务列表
  const fetchTasks = async (status) => {
    setLoading(true)
    try {
      // 替换为实际API调用
      const response = await fetch(`/api/tasks?status=${status}`)
      const data = await response.json()
      setTasks((prev) => ({
        ...prev,
        [status]: data,
      }))
    } catch (error) {
      message.error("获取任务列表失败")
    } finally {
      setLoading(false)
    }
  }

  // 处理任务状态变更
  const handleStatusChange = async (taskId, newStatus) => {
    try {
      // 替换为实际API调用
      await fetch(`/api/tasks/${taskId}/status`, {
        method: "PUT",
        body: JSON.stringify({ status: newStatus }),
      })
      message.success("状态更新成功")
      // 重新获取相关状态的任务列表
      fetchTasks(activeTab)
    } catch (error) {
      message.error("状态更新失败")
    }
  }

  // 优先级标签颜色映射
  const priorityColors = {
    high: "red",
    medium: "orange",
    low: "green",
  }

  // 任务列表渲染
  const renderTaskList = (tasks, status) => (
    <List
      className="task-list"
      loading={loading}
      itemLayout="horizontal"
      dataSource={tasks}
      renderItem={(task) => (
        <List.Item actions={renderActions(task, status)}>
          <List.Item.Meta
            avatar={
              <Badge status={task.status === "urgent" ? "error" : "default"}>
                <Avatar src={task.assignerAvatar} icon={<UserOutlined />} />
              </Badge>
            }
            title={
              <Space>
                <span>{task.title}</span>
                <Tag color={priorityColors[task.priority]}>
                  <ExclamationCircleOutlined /> {task.priority}
                </Tag>
              </Space>
            }
            description={
              <Space direction="vertical" size={2}>
                <Space>
                  <CalendarOutlined /> 截止日期：{task.deadline}
                  <span>|</span>
                  发起人：{task.creator}
                </Space>
                <Progress percent={task.progress} size="small" />
                <div>{task.description}</div>
              </Space>
            }
          />
        </List.Item>
      )}
    />
  )

  // 根据任务状态渲染不同的操作按钮
  const renderActions = (task, status) => {
    switch (status) {
      case "todo":
        return [
          <Button
            key="start"
            type="link"
            onClick={() => handleStatusChange(task.id, "inProgress")}
          >
            开始处理
          </Button>,
        ]
      case "inProgress":
        return [
          <Button
            key="complete"
            type="link"
            onClick={() => handleStatusChange(task.id, "completed")}
          >
            完成
          </Button>,
          <Button
            key="return"
            type="link"
            onClick={() => handleStatusChange(task.id, "todo")}
          >
            退回
          </Button>,
        ]
      case "completed":
        return [
          <Button
            key="reopen"
            type="link"
            onClick={() => handleStatusChange(task.id, "inProgress")}
          >
            重新开启
          </Button>,
        ]
      default:
        return []
    }
  }

  useEffect(() => {
    fetchTasks(activeTab)
  }, [activeTab])

  const items = [
    {
      key: "todo",
      label: (
        <span>
          <ClockCircleOutlined />
          待办任务
          <Badge count={tasks.todo.length} style={{ marginLeft: 8 }} />
        </span>
      ),
      children: renderTaskList(tasks.todo, "todo"),
    },
    {
      key: "inProgress",
      label: (
        <span>
          <SyncOutlined spin />
          进行中
          <Badge count={tasks.inProgress.length} style={{ marginLeft: 8 }} />
        </span>
      ),
      children: renderTaskList(tasks.inProgress, "inProgress"),
    },
    {
      key: "completed",
      label: (
        <span>
          <CheckCircleOutlined />
          已完成
          <Badge count={tasks.completed.length} style={{ marginLeft: 8 }} />
        </span>
      ),
      children: renderTaskList(tasks.completed, "completed"),
    },
  ]

  return (
    <>
      <PageHeaderWrapper title="我的协同" subtitle="管理您的协同任务" />
      <section className="G-main">
        <Card>
          <Tabs activeKey={activeTab} items={items} onChange={setActiveTab} />
        </Card>
      </section>
    </>
  )
}

export default MyCollaboration
